/**
 * Created by 小敏哥 on 2017/10/19.
 */
/**
 * Created by 小敏哥 on 2017/6/15.
 */
/**
 * Created by 小敏哥 on 2017/4/10.
 */
import appUserHelper from './userHelper';
import jsApi from './cx580.jsApi';
import urlOperation from './urlOperation';
import timeOutLocalStorage from './timeOutLocalStorage';
import typeOfBrowser from './typeOfBrowser';
import tmallLoginService from '../services/tmallLoginService';
import CryptoJS from 'crypto-js';
import cookiesOperation from './cookiesOperation';

class Login {
    constructor() {
        this.channel = this.compatible((urlOperation.getParameters().detailUserType||cookiesOperation.getCookie("userType")).toLowerCase()).toLowerCase();
        if (location.href.indexOf('%23') > -1) {
            location.href = location.href.replace('%23', '#');
        }
    }

    //临时兼容旧版本
    compatible(userType) {
        switch (userType) {
            case undefined:
                return 'alipaycitys2017';
            case '':
                return 'alipaycitys2017';
            case 'alipay_city':
                return 'alipaycitys2017';
            case 'qq_city':
                return 'qqqianbao2017';
            case 'alipay_carservice':
                return 'alipaycarservice';
            default:
                return userType;
        }
    }

    //根据不同渠道获取单点登录参数
    _getTypeByChannel() {
        var type = {};
        switch (this.channel) {
            case undefined:
                type = {
                    authType: 'alipaycityservice',
                    userType: 'alipaycitys2017'
                };
                break;
            case 'alipaycitys2017':
                type = {
                    authType: 'alipaycityservice',
                    userType: 'alipaycitys2017'
                };
                break;
            case 'alipay':
                type = {
                    authType: 'alipay',
                    userType: 'alipay'
                };
                break;
            case 'alqc2017':
                type = {
                    authType: 'alipay',
                    userType: 'alqc2017'
                };
                break;
            case 'alipaycarservice':
                type = {
                    authType: 'alipay',
                    userType: 'alipaycarservice'
                };
                break;
            case 'alipayshh2016':
                type = {
                    authType: 'alipay',
                    userType: 'alipayshh2016'
                };
                break;
            case 'weixin':
                type = {
                    authType: 'weixin',
                    userType: 'weixin'
                };
                break;
            case 'youche2017':
                type = {
                    authType: 'weixin',
                    userType: 'youche2017'
                };
                break;
            case 'qqqianbao2017':
                type = {
                    authType: 'qqcityservice',
                    userType: 'qqqianbao2017'
                };
                break;
            case 'qq':
                type = {
                    authType: 'qq',
                    userType: 'qq'
                };
                break;
            default:
                type = {
                    authType: 'sms',
                    userType: this.channel
                };
        }
        return type;
    }

    //获取当前时间与缓存用户信息时间差
    getSbuDays(localDateString) {
        let now = new Date();
        let localDate = new Date(localDateString);
        let days = (now.getTime() - localDate.getTime()) / (1000 / 3600);
        return days;
    }

    //单点登录
    _singleSignOn() {
        var search = '?' + window.location.href.split('?')[1];
        //此处仅供调试使用，本地写死登录信息，无需登录
        if (window.location.host.indexOf("localhost") !== -1) {
            //此处仅供本地调用如果本地缓存中存在用户信息则直接复制到session中供代码调用
            sessionStorage.setItem("userId", localStorage.getItem("userId"));
            sessionStorage.setItem("token", localStorage.getItem("token"));
            sessionStorage.setItem("userType", localStorage.getItem("userType"));
            sessionStorage.setItem("authType", localStorage.getItem("authType"));
            sessionStorage.setItem("openId", localStorage.getItem("openId"));
            return true;
        }
        //从cookies读取数据
        else if (cookiesOperation.getCookie('userId') && cookiesOperation.getCookie('userToken')) {
            sessionStorage.setItem("userId", cookiesOperation.getCookie("userId"));
            sessionStorage.setItem("token", cookiesOperation.getCookie("userToken"));
            sessionStorage.setItem("userType", cookiesOperation.getCookie("userType"));
            sessionStorage.setItem("authType", cookiesOperation.getCookie("userAuthType"));
            sessionStorage.setItem("openId", cookiesOperation.getCookie("userOpenId"));
            //detailUserType多处使用，均引用自localStorage
            localStorage.setItem("detailUserType", this.channel);
            return true;
        }
        //此处为走后端单点登录后带完整信息的分支
        else if (urlOperation.getParameters().userId) {
            //首页登录之后回到页面，执行初始化信息操作
            var userId = '';
            userId = urlOperation.getParameters().userId;
            sessionStorage.setItem("userId", userId); //保存openId
            var token = urlOperation.getParameters().token;
            sessionStorage.setItem("token", token); //保存token
            var userType = urlOperation.getParameters().userType;
            sessionStorage.setItem("userType", userType); //保存userType
            var openId = urlOperation.getParameters().userOpenId;
            sessionStorage.setItem("openId", openId); //保存openId
            var authType = urlOperation.getParameters().authType;
            sessionStorage.setItem("authType", authType); //保存authType
            //用户信息缓存本地，失效时间为24小时
            timeOutLocalStorage.setItem("userId", userId, 1000 * 60 * 60 * 24);
            timeOutLocalStorage.setItem("token", token, 1000 * 60 * 60 * 24);
            timeOutLocalStorage.setItem("userType", userType, 1000 * 60 * 60 * 24);
            timeOutLocalStorage.setItem("openId", openId, 1000 * 60 * 60 * 24);
            //detailUserType多处使用，均引用自localStorage
            localStorage.setItem("detailUserType", this.channel);
            return true;
        }
        //读取缓存的用户信息，此处是用于支付完成之后跳转到订单详情使用，----加上判断，当且仅当地址为支付后跳转地址才获取缓存
        else if (location.hash.length > 2 && timeOutLocalStorage.getItem("userId")) {
            sessionStorage.setItem("userId", timeOutLocalStorage.getItem("userId"));
            sessionStorage.setItem("token", timeOutLocalStorage.getItem("token"));
            sessionStorage.setItem("userType", timeOutLocalStorage.getItem("userType"));
            sessionStorage.setItem("openId", timeOutLocalStorage.getItem("openId"));
            sessionStorage.setItem("authType", timeOutLocalStorage.getItem("authType"));
            return true;
        }
        else {
            var loginType = this._getTypeByChannel();
            //追加本地缓存渠道号进行单点登录
            var authIstest = location.protocol + "//" + location.host + "/"; //正式||测试 单点登录
            //单点登录返回地址仅能带一个参数，单点登录之前缓存详细渠道信息，防止
            // 登录之后参数丢失
            localStorage.setItem('detailUserType', this.channel);
            window.location.replace(`${authIstest}user/bindInfo?userType=${loginType.userType}`);
            /*var authIstest ="http://local-test.cx580.com:3000/api/login/bindInfo";
            localStorage.setItem('detailUserType', this.channel);
            window.location.replace(`${authIstest}?userType=${loginType.userType}`);*/
            return false;
        }
    }


    //app登录
    _appLogin(callBack) {
        setTimeout(() => {
            appUserHelper.getUserIdAndTokenWithCallBack(() => {
                if (!sessionStorage.getItem("userId")) {
                    appUserHelper.Login(callBack, () => {
                        jsApi.call(
                            {
                                "commandId": "",
                                "command": "close"
                            });
                    });
                }
                else {
                    callBack();
                }
            })
        }, 300);
        //缓存当前渠道，走app登录的都为app渠道
        localStorage.setItem("detailUserType", 'app');
    }

    //app登录（对外方法）
    appLogin(callBack) {
        if (navigator.userAgent.indexOf("appname_cxycwz") > -1) {
            this._appLogin(callBack);
        }
        else {
            callBack();
        }
    }

    //强制重新登录，跳过从getsymbol获取用户信息
    appLoginWithoutCheck(callBack){
        appUserHelper.Login(callBack, () => {
            jsApi.call(
                {
                    "commandId": "",
                    "command": "close"
                });
        });
    }

    //app端记录机器id
    recordMachineId() {
        jsApi.call({
            "commandId": "",
            "command": "getSymbol",
            "data": {
                "userid": "",
                "deviceId": "",
            }
        }, (data) => {
            localStorage.setItem("machineId", data.data.deviceId || data.data.userid);
        });
    }

    //从后台将天猫登录信息转化为内部登录信息
    changeUserInformation(data, callBack) {
        tmallLoginService.login(data).then((result) => {
            if (result.code == '0') {
                sessionStorage.setItem("userId", result.data.userId);
                sessionStorage.setItem("token", result.data.token);
                sessionStorage.setItem("userType", result.data.userType);
                //缓存用户信息，用于收银台回跳
                timeOutLocalStorage.setItem("userId", result.data.userId, 1000 * 60 * 60 * 24);
                timeOutLocalStorage.setItem("token", result.data.token, 1000 * 60 * 60 * 24);
                timeOutLocalStorage.setItem("userType", result.data.userType, 1000 * 60 * 60 * 24);
                //缓存detailUserType备用
                localStorage.setItem("detailUserType", result.data.userType);
                callBack();
            }
            else {
                alert(result.message);
            }
        });
    }

    //天猫商城登录
    tmallLogin(callBack) {
        //isTmall为收银台支付成功后天猫渠道带回的特定标识，此时无用户信息，会从缓存中读取
        if (urlOperation.getParameters()['isTmall'] == 'true') {
            if (timeOutLocalStorage.getItem("userId")) {
                sessionStorage.setItem("userId", timeOutLocalStorage.getItem("userId"));
                sessionStorage.setItem("token", timeOutLocalStorage.getItem("token"));
                sessionStorage.setItem("userType", timeOutLocalStorage.getItem("userType"));
                localStorage.setItem("detailUserType", timeOutLocalStorage.getItem("userType"));
                callBack();
            }
            else {
                alert('登录信息过期！')
            }
        }
        else {
            //淘宝我的爱车渠道会带回渠道登录信息
            if (urlOperation.getParameters()['user_from'] && urlOperation.getParameters()['sign']) {
                let data = {
                    user_id: urlOperation.getParameters()['user_id'],
                    user_from: urlOperation.getParameters()['user_from'],
                    carnumber: decodeURIComponent(urlOperation.getParameters()['carnumber']),
                    carcode: urlOperation.getParameters()['carcode'],
                    cardrive: urlOperation.getParameters()['cardrive'],
                    sign: urlOperation.getParameters()['sign'],
                };
                this.changeUserInformation(data, callBack);
            }
            else {
                //天猫渠道无用户信息，从sdk获取
                let options = {
                    sellerNick: "车行易旗舰店"
                };

                let user_from = 'CXYTMALL';
                Tida && Tida.ready({
                    sellerNick: "车行易旗舰店", // 商家名称
                    shopId: 558702026, // 店铺ID 从url中取 可选
                    console: 1
                }, () => {
                    Tida.mixNick(options, (data) => {
                        if (data.mixnick) {
                            let text = `${data.mixnick + user_from}6D54AE366CA44A22AB1604B067594A3A`;
                            let sign = CryptoJS.MD5(text).toString();
                            let params = {
                                user_id: data.mixnick,
                                user_from: user_from,
                                sign: sign
                            };
                            this.changeUserInformation(params, callBack);
                        }
                    })
                });
            }
        }
    }

    loginOperation(callBack) {
        //isTmall为收银台支付成功后天猫渠道带回的特定标识，此时无用户信息，会从缓存中读取
        if (urlOperation.getParameters()['isTmall'] == 'true' || window.location.href.indexOf('jaeapp.com') > -1) {
            this.tmallLogin(callBack)
        }
        else if (typeOfBrowser.getChannelOfBrowser() != 'app') {
            this._singleSignOn() && callBack();
        }
        else {
            /*localStorage.setItem("detailUserType",'app');
            //app模式下延迟登录，等到请求接口报错时，再回来登录
            callBack();*/
            this._appLogin(callBack);
            this.recordMachineId();
        }
    }
}

export default new Login();